package com.itheima.sys.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.itheima.common.util.JsonUtils;
import com.itheima.sys.properties.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @description:
 **/
@Slf4j
@Component
public class SmsHelper {

    @Autowired
    private IAcsClient client;

    @Autowired
    private SmsProperties prop;

    /**
     * 发送短信工具方法
     * @param phone 手机号
     * @param templateCode 短信模板
     * @param paramJson 模板参数 格式为json
     */
    public void sendSms(String phone, String templateCode, String paramJson){
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(prop.getDomain());  //发送请求目标服务器
        request.setVersion(prop.getVersion());
        request.setAction(prop.getAction());  //调用方法名称
        request.putQueryParameter("RegionId", prop.getRegionID());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", prop.getSignName());
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", paramJson);
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            String ret  = response.getData(); //格式
            Map<String, String> mapResult = JsonUtils.toMap(ret, String.class, String.class);
            if(mapResult.get("Code").equals("OK")){
                log.info("发送短信成功:{}", phone);
            }else{
                log.error("【短信服务】发送短信失败，失败原因："+mapResult.get("Message"));
                //发送邮件通知管理员
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
